package com.func.domain.activity.service.partake;

import com.func.domain.activity.model.aggregate.CreatePartakeOrderAggregate;
import com.func.domain.activity.model.entity.*;
import com.func.domain.activity.model.valobj.UserRaffleOrderStateVO;
import com.func.domain.activity.repository.IActivityRepository;
import com.func.domain.strategy.service.IRaffleStrategy;
import com.func.types.enums.ResponseCode;
import com.func.types.exception.AppException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * RaffleActivityPartakeService
 * </p>
 *
 * @author Simon
 * @version 2025.03.14.1.0.0
 * @description
 * @since 2025-03-14
 */

@AllArgsConstructor
@Service
@Slf4j
public class RaffleActivityPartakeService extends AbstractRaffleActivityPartake{
    private IActivityRepository activityRepository;

    private final SimpleDateFormat dateFormatMonth = new SimpleDateFormat("yyyy-MM");
    private final SimpleDateFormat dateFormatDay = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    protected IRaffleStrategy raffleStrategy;
    @Override
    protected CreatePartakeOrderAggregate doFilterAccount(String userId, Long activityId, Date currentDate) {
        // 查询总账户额度
        ActivityAccountEntity activityAccountEntity =  activityRepository.queryActivityAccountByUserId(userId, activityId);

        // 额外判断, 我们需要确保用户总额度账户一定不为空
        if (null == activityAccountEntity || activityAccountEntity.getTotalCountSurplus() <= 0) {
            log.error("查询用户总额度失败: 不存在账户 userId: {}, activityId: {}, currentDate: {}", userId, activityId, currentDate);
            throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
        }

        String month = dateFormatMonth.format(currentDate);
        String day = dateFormatDay.format(currentDate);

        // 查询月额度
        ActivityAccountMonthEntity activityAccountMonthEntity = activityRepository.queryActivityAccountMonthByUserId(userId, activityId, month);
        if (null != activityAccountMonthEntity && activityAccountMonthEntity.getMonthCountSurplus() <= 0) {
            log.error("查询用户月额度失败: 不存在账户 userId: {}, activityId: {}, currentDate: {}", userId, activityId, currentDate);
            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
        }

        // 创建月账户额度: true = 存在月账户, false = 不存在月账户
        boolean existAccountMonth = null != activityAccountMonthEntity;
        if (!existAccountMonth) {
            activityAccountMonthEntity = new ActivityAccountMonthEntity();
            activityAccountMonthEntity.setActivityId(activityId);
            activityAccountMonthEntity.setUserId(userId);
            activityAccountMonthEntity.setMonth(month);
            activityAccountMonthEntity.setMonthCount(activityAccountEntity.getMonthCount());
            activityAccountMonthEntity.setMonthCountSurplus(activityAccountEntity.getMonthCount());
        }

        // 查询日额度
        ActivityAccountDayEntity activityAccountDayEntity = activityRepository.queryActivityAccountDayByUserId(userId, activityId, day);
        if (null != activityAccountDayEntity && activityAccountDayEntity.getDayCountSurplus() <= 0){
            log.error("查询用户日额度失败: 不存在账户 userId: {}, activityId: {}, currentDate: {}", userId, activityId, currentDate);
            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
        }

        // 创建日账户余额: true = 存在日账户, false = 不存在日账户
        boolean existAccountDay = null != activityAccountDayEntity;
        if (!existAccountDay) {
            activityAccountDayEntity = new ActivityAccountDayEntity();
            activityAccountDayEntity.setActivityId(activityId);
            activityAccountDayEntity.setDay(day);
            activityAccountDayEntity.setUserId(userId);
            activityAccountDayEntity.setDayCount(activityAccountEntity.getDayCount());
            activityAccountDayEntity.setDayCountSurplus(activityAccountEntity.getDayCount());
        }


        // 构建返回对象
        return CreatePartakeOrderAggregate.builder()
                .activityId(activityId)
                .userId(userId)
                .activityAccountDayEntity(activityAccountDayEntity)
                .activityAccountMonthEntity(activityAccountMonthEntity)
                .activityAccountEntity(activityAccountEntity)
                .existAccountDay(existAccountDay)
                .activityAccountDayEntity(activityAccountDayEntity)
                .existAccountMonth(existAccountMonth)
                .activityAccountMonthEntity(activityAccountMonthEntity)
                .build();
    }

    @Override
    protected UserRaffleOrderEntity buildUsrRaffleOrder(String userId, Long activityId, Date currentDate) {
        // 查询基本信息
        ActivityEntity activity = activityRepository.queryRaffleActivityByActivityId(activityId);

        // 构建返回
        return UserRaffleOrderEntity.builder()
                .activityId(activityId)
                .activityName(activity.getActivityName())
                .strategyId(activity.getStrategyId())
                .userId(userId)
                .orderTime(currentDate)
                .orderId(RandomStringUtils.randomNumeric(12))
                .orderState(UserRaffleOrderStateVO.create)
                .endDateTime(activity.getEndDateTime())
                .build();
    }
}
